package com.qiu.DitingPlatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiu.DitingPlatform.common.BaseResponse;
import com.qiu.DitingPlatform.common.ErrorCode;
import com.qiu.DitingPlatform.common.ResultUtils;
import com.qiu.DitingPlatform.model.domain.User;
import com.qiu.DitingPlatform.model.domain.request.UserLoginRequest;
import com.qiu.DitingPlatform.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.qiu.DitingPlatform.model.domain.request.UserRegisterRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.qiu.DitingPlatform.contant.UserConstant.ADMIN_ROLE;
import static com.qiu.DitingPlatform.contant.UserConstant.USER_Login_STATE;
import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;


/**
 * 用户接口
 *
 * @author ：qiu
 */
@RestController
@RequestMapping("/user")
public class userController {

    @Resource
    private UserService userService;


    /**
     * 注册接口
     *
     * @param userRegisterRequest 注册请求体
     * @return 用户id
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {

        if (userRegisterRequest == null) {
            return ResultUtils.error(ErrorCode.PARAM_ERROR, "注册请求体为空");
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String plantcode = userRegisterRequest.getPlantcode();

        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword, plantcode)) {
            return ResultUtils.error(ErrorCode.PARAM_NOT_NULL);
        }

        Long id = userService.userRegister(userAccount, userPassword, checkPassword, plantcode);

//        return new BaseResponse<>(0, id, "注册成功");
        return ResultUtils.success(id);
    }

    /**
     * 登录接口
     *
     * @param UserLoginRequest 用户登录接口
     * @return 用户脱敏信息
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest UserLoginRequest, HttpServletRequest request) {

        if (UserLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAM_NOT_NULL);
        }
        String userAccount = UserLoginRequest.getUserAccount();
        String userPassword = UserLoginRequest.getUserPassword();

        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAM_NOT_NULL);
        }

        User user = userService.userLogin(userAccount, userPassword, request);
//        return new BaseResponse<>(0, user, "登录成功");
        return ResultUtils.success(user);
    }

    /**
     * 管理员查询用户信息
     *
     * @param userName 用户名字
     * @param request  请求体 取session
     * @return 用户信息
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUser(String userName, HttpServletRequest request) {
        // 仅管理员可以访问
        if (!isAdmin(request)) {
            return ResultUtils.error(ErrorCode.NO_AUTH);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(userName)) {
            queryWrapper.like("username", userName);
        }
        List<User> userList = userService.list(queryWrapper);

        List<User> list = userList.stream().map(user -> userService.geySafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    /**
     * 管理员删除用户
     *
     * @param id      用户id
     * @param request 请求体 取session
     * @return boolean
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody Long id, HttpServletRequest request) {
        // 仅管理员可以访问
        if (!isAdmin(request)) {
            return ResultUtils.error(ErrorCode.NO_AUTH);
        }
        // 判断id是否合法
        if (id < 0) {
            return ResultUtils.error(ErrorCode.PARAM_ERROR);
        }
//        return userService.removeById(id);
        return ResultUtils.success(userService.removeById(id));
    }

    /**
     * 管理员更新用户信息
     *
     * @param request 请求体 取session
     * @return User 脱敏信息
     */

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        // 取session
        Object userObj = request.getSession().getAttribute(USER_Login_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            return ResultUtils.error(ErrorCode.NO_LOGIN);
        }
        Long id = currentUser.getId();

        User user = userService.getById(id);

        return ResultUtils.success(user);
    }

    /**
     * 判断是否是管理员
     *
     * @param request 请求体 取session
     * @return boolean
     */
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可以访问
        Object userObj = request.getSession().getAttribute(USER_Login_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }

    /**
     * 退出登录
     *
     * @param request 请求体
     * @return 退出 1 成功 null 失败
     */
    @PostMapping("/logout")
    public BaseResponse<String> userLogout(HttpServletRequest request) {
        if (request == null) {
            return ResultUtils.error(ErrorCode.NO_LOGIN);
        }
//        return userService.userLogout(request);
        return ResultUtils.success(userService.userLogout(request));
    }

}

